<template>
  <div>
    <ConditionCard
      shadow="never"
      body-style="padding: 24px 24px 6px 24px;"
      @search="onSearch"
      @reset="onReset"
    >
      <el-form ref="queryForm" :model="queryForm" label-position="right" label-width="80px">
        <el-row>
          <!-- 年级-->
          <el-col :span="8">
            <el-form-item :label="$t('preparatoryGraduation.common.grade')">
              <el-date-picker
                v-model="queryForm.grade"
                value-format="yyyy"
                align="right"
                type="year"
                @change="handleGradeChange"
                :placeholder="$t('common.pla.pleaseSelect')"
                clearable
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <!-- 学院 -->
          <el-col :span="8">
            <el-form-item :label="$t('preparatoryGraduation.common.college')">
              <DictSelect v-model="queryForm.college" :data="source.colleges" @change="handleCollegeChange"/>
            </el-form-item>
          </el-col>
          <!-- 专业 -->
          <el-col :span="8">
            <el-form-item :label="$t('preparatoryGraduation.common.major')">
              <DictSelect v-model="queryForm.major" :data="source.majors"/>
            </el-form-item>
          </el-col>
          <!-- 性别 -->
          <el-col :span="8">
            <el-form-item label="性别">
              <DictSelect v-model="queryForm.sex" :data="source.sexes"/>
            </el-form-item>
          </el-col>
          <!-- 结业年份 -->
          <el-col :span="8">
            <el-form-item label="结业年份">
              <el-date-picker
                v-model="queryForm.completionYear"
                value-format="yyyy"
                align="right"
                type="year"
                :placeholder="$t('common.pla.pleaseSelect')"
                clearable
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <!-- 结业状态 -->
          <el-col :span="8">
            <el-form-item label="结业状态">
              <DictSelect v-model="queryForm.status" :data="source.status"/>
            </el-form-item>
          </el-col>
          <!-- 离校时间 -->
          <el-col :span="8">
            <el-form-item label="离校时间">
              <el-date-picker
                v-model="timeRange.offSchool"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="timeRangeChange('offSchool', 'offSchoolStart', 'offSchoolEnd')"
                :picker-options="pickerOptions"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <!-- 证书编码-->
          <el-col :span="8">
            <el-form-item label="证书编码">
              <el-input v-model="queryForm.certificateNo"/>
            </el-form-item>
          </el-col>
          <!-- 身份证号 -->
          <el-col :span="8">
            <el-form-item label="身份证号">
              <el-input v-model="queryForm.number"/>
            </el-form-item>
          </el-col>
          <!-- 入学时间 -->
          <el-col :span="8">
            <el-form-item label="入学时间">
              <el-date-picker
                v-model="timeRange.enrollmentDate"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="timeRangeChange('enrollmentDate', 'enrollmentDateStart', 'enrollmentDateEnd')"
                :picker-options="pickerOptions"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </ConditionCard>
    <el-card shadow="never" body-style="padding: 24px;">
      <div class="edu-page-title mg-bottom leftPadding">
        <span>毕业学生名单列表</span>
      </div>
      <div class="float-left">
        <el-input
          v-model.trim="queryForm.searchText"
          placeholder="请输入学生姓名或学号"
          prefix-icon="el-icon-search"
          @change="loadTableData"
        />
      </div>
      <div class="float-right">
        <div class="clearfix mg-bottom">
          <el-row>
            <!--<el-button type="primary">预科资格核对(学信网)</el-button>-->
            <!--<el-button type="primary">预科拍照名单</el-button>
            <el-button type="primary">证书发放名单</el-button>-->
          </el-row>
        </div>
        <div class="clearfix mg-bottom">
          <el-row>
           <!-- <el-button type="primary">未结业学生名单</el-button>-->
            <el-button type="primary" @click="batchDownloadSchoolReports">成绩单下载</el-button>
            <el-button type="primary" @click="showBatchDialog">批量离校时间设置</el-button>
            <!--<el-button type="primary">证书发放审核表</el-button>
            <el-button type="primary">结业证书打印表</el-button>-->
          </el-row>
        </div>
      </div>
      <EduTable
        ref="table"
        :data="tableData"
        :total="page.total"
        :pageSize="page.pageSize_"
        :pageNum="page.pageNum_"
        :order="false"
        :select-on-indeterminate="false"
        class="scoreTableMarginTop"
        @page-change="onPageChange"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          label="学号"
          prop="studentId"
          show-overflow-tooltip
          min-width="100"
          align="center"
          fixed="left"
        />
        <el-table-column
          label="姓名"
          prop="name"
          show-overflow-tooltip
          min-width="100"
          align="center"
          fixed="left"
        />
        <el-table-column
          label="学院"
          prop="collegeI18n"
          show-overflow-tooltip
          min-width="110"
          align="center"
          fixed="left"
        />
        <el-table-column
          label="身份证号"
          prop="number"
          show-overflow-tooltip
          min-width="140"
          align="center"
        />
        <el-table-column
          label="性别"
          prop="sexI18n"
          show-overflow-tooltip
          min-width="60"
          align="center"
        />
        <el-table-column
          label="出生日期"
          prop="birthday"
          show-overflow-tooltip
          min-width="110"
          align="center"
        />
        <el-table-column
          label="专业"
          prop="majorI18n"
          show-overflow-tooltip
          min-width="140"
          align="center"
        />
        <el-table-column
          label="年级"
          prop="grade"
          show-overflow-tooltip
          min-width="80"
          align="center"
        />
        <el-table-column
          label="入学时间"
          prop="enrollmentDate"
          show-overflow-tooltip
          min-width="110"
          align="center"
        />
        <el-table-column
          label="离校时间"
          min-width="120"
          align="center"
        >
          <template slot-scope="scope">
            <el-date-picker
              v-if="scope.row.flag"
              v-model="scope.row.offSchool"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="选择日期">
            </el-date-picker>
            <span v-else>{{scope.row.offSchool}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="结业年份"
          prop="completionYear"
          show-overflow-tooltip
          min-width="80"
          align="center"
        />
        <el-table-column
          label="结业证书编号"
          prop="certificateNo"
          show-overflow-tooltip
          min-width="130"
          align="center"
        />
        <el-table-column
          label="结业状态"
          prop="status"
          show-overflow-tooltip
          min-width="80"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag v-if="(scope.row.status || 1).toString() === '1'" type="danger" size="mini">未结业</el-tag>
            <el-tag v-if="(scope.row.status || 1).toString() === '2'" type="success" size="mini">已结业</el-tag>
            <el-tag v-if="(scope.row.status || 1).toString() === '3'" type="warning" size="mini">退回生源地</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          show-overflow-tooltip
          min-width="110"
          align="center"
        >
          <template slot-scope="scope">
            <el-button type="text" @click="scope.row.flag = true;onEdit(scope.row)" v-if="!scope.row.flag">编辑</el-button>
            <el-button type="text" @click="scope.row.flag = false;onSave(scope.row)" v-if="scope.row.flag">保存</el-button>
            <el-button type="text" @click="scope.row.flag = false;onCancel(scope.row)" v-if="scope.row.flag">取消</el-button>
          </template>
        </el-table-column>
      </EduTable>
    </el-card>
    <edu-dialog
      title="批量设置离校时间"
      ref="offSchoolDialog"
      @confirm="batchSetOffSchool"
      @open="offSchool = null"
      width="30%"
    >
      <el-form label-position="right" label-width="80px">
        <el-form-item label="离校时间">
          <el-date-picker
            v-model="offSchool"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
    </edu-dialog>
    <edu-export-dialog ref="downloadTipDialog" :data="downloadResult"/>
  </div>
</template>
<script>
  import request from 'common/src/api/preparatoryGraduation/completionManagement';
  import completionAudit from '../completionAudit.js';
  export default {
    name: 'completionManagement',
    mixins: [completionAudit],
    data() {
      return {
        defaultQueryForm: {
          grade: (new Date().getFullYear() - 1).toString(),
          college: '',
          major: '',
          sex: '',
          completionYear: '',
          status: '',
          certificateNo: '',
          number: '',
          searchText: '',
          enrollmentDateStart: '',
          enrollmentDateEnd: '',
          offSchoolStart: '',
          offSchoolEnd: ''
        },
        queryForm: {},
        timeRange: {
          enrollmentDate: [],
          offSchool: []
        },
        selectedTableData: [],
        offSchool: '',
        downloadResult: null,
        originalRows: {}
      };
    },
    created() {
      this.queryForm = Object.assign({}, this.defaultQueryForm);
    },
    mounted() {
      this.loadTableData();
    },
    methods: {
      onSearch() {
        this.loadTableData();
      },
      onReset() {
        this.queryForm = Object.assign({}, this.defaultQueryForm);
        this.timeRange = {
          enrollmentDate: [],
          offSchool: []
        };
        this.page = Object.assign({}, this.defaultPage);
        this.$refs['queryForm'].resetFields();
        this.loadTableData();
      },
      onPageChange(page) {
        this.page.pageNum_ = page.pageNum;
        this.page.pageSize_ = page.pageSize;
        this.loadTableData();
      },
      loadTableData() {
        this.triggingLoading();
        request.pageList({...this.queryForm, ...this.page}).then(res => {
          const data = res.data;
          this.tableData = data.list;
          this.page = {
            total: data.total_,
            pageNum_: data.pageNum_,
            pageSize_: data.pageSize_
          };
          this.triggingLoading();
        });
      },
      timeRangeChange(key, start, end) {
        if (this.timeRange[key] && this.timeRange[key].length) {
          const value = this.timeRange[key];
          this.queryForm[start] = this.dateFormat(value[0]);
          this.queryForm[end] = this.dateFormat(value[1]);
        }
      },
      handleSelectionChange(data) {
        this.selectedTableData = data;
      },
      onEdit(row) {
        this.originalRows[row.studentId] = row.offSchool;
      },
      onSave(row) {
        this.triggingLoading();
        const params = {
          grade: row.grade,
          studentId: row.studentId,
          offSchoolStr: row.offSchool
        };
        request.setOffSchoolDate(params).then(() => {
          this.triggingLoading();
        });
      },
      onCancel(row) {
        row.offSchool = this.originalRows[row.studentId];
      },
      showBatchDialog() {
        if (!this.selectedTableData || this.selectedTableData.length < 1) {
          this.$noSelectAlert();
          return;
        }
        this.$refs['offSchoolDialog'].open();
      },
      /**
       * 批量设置离校时间
       * */
      batchSetOffSchool() {
        if (!this.offSchool) {
          this.$eduAlert('请先选择离校日期','提示');
          return false;
        }
        const list = [];
        this.selectedTableData.forEach(item => {
          list.push({
            grade: item.grade,
            studentId: item.studentId,
            offSchoolStr: this.offSchool
          });
        });
        request.batchSetOffSchoolDate({ list }).then(() => {
          this.$refs['offSchoolDialog'].close();
          this.loadTableData();
        });
      },
      // 成绩单下载
      batchDownloadSchoolReports() {
        if (!this.selectedTableData || this.selectedTableData.length < 1) {
          this.$noSelectAlert();
          return;
        }
        const studentIds = this.selectedTableData.map(item => item.studentId);
        const params = {
          studentIds: String(studentIds),
          language: 'cn'
        };
        this.downloadResult = null;
        this.$refs['downloadTipDialog'].open();
        request.batchDownloadSchoolReports(params).then(res => {
          this.delayRequestDown(res.data.key);
        });
      },
      /**
       * 延迟处理下载文件的请求
       * @param key
       * @param delayTime,单位：ms, 默认500
       */
      delayRequestDown(key, delayTime = 500) {
        setTimeout(() => {
          request.exportBatchForKey(key).then(res => {
            this.downloadResult = res.data;
            window.open(`/api/scoremanagementservice/scorePrint/scoresheet/downloadZip?path=${res.data.path}`);
            this.$refs['downloadTipDialog'].close();
            const failedIds = res.data.failedId;
            failedIds && failedIds.length && this.showFailDownloadTip(res.data.total, failedIds);
          });
        }, delayTime);
      },
      /**
       * 成绩单下载失败的提示框
       * @param successNum
       * @param failNum
       */
      showFailDownloadTip(successNum, failNum){
        this.$confirm(
          `已下载${successNum}条数据。另有${failNum.length}条数据下载失败,学号为:${String(failNum)}`,
          '提示',
          {
            cancelButtonText:'关闭',
            showCancelButton:'false',
            showConfirmButton:false
          }
        );
      }
    }
  };
</script>
<style lang="scss" scoped>
  .mg-bottom{
    margin-bottom: 15px;
  }
  .edu-page-title {
    span {
      line-height: 24px;
      display: inline-block;
      padding-right: 10px;
      font-size: 18px;
      font-weight: bold;
      color: #2b3b4e;
    }
  }
</style>
